﻿using System;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;

namespace Eneta.Portal.Companies.Controls
{
    public class IOHeaderControl : UserControl
    {
        protected DropDownList productsDropDown;
        protected HtmlGenericControl noLevelBlock;
        protected HtmlGenericControl level1Block;
        protected HtmlGenericControl level2Block;
        protected HtmlGenericControl productBlock;
        protected HtmlAnchor level1TitleLink;
        protected HtmlAnchor level2TitleLink;
        protected HtmlAnchor productTitleLink;

        protected Repeater productsRepeater;
        protected DropDownList productLevel1;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            productsDropDown.SelectedIndexChanged += ProductsDropDownSelectedIndexChanged;
            productsRepeater.ItemDataBound += ProductsRepeaterItemDataBound;
            productLevel1.SelectedIndexChanged += ProductLevel1SelectedIndexChanged;
        }

        void ProductLevel1SelectedIndexChanged(object sender, EventArgs e)
        {
            var id = productLevel1.SelectedValue;
            Response.Redirect("/firmad/Lehed/Default.aspx?l3=" + id + "&p=" + Request.QueryString["p"]);
            Response.End();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (IsPostBack)
                return;

            var repository = new CompanyRepository(SPContext.Current.Web);

            try
            {
                //var products = CompanyQueryManager.GetAllProducts();
                var products = repository.GetAllProductsResults();
                if (products != null)
                    if (products.Count > 0)
                        products = products.OrderBy(prd => prd.Title).ToList();

                productsDropDown.DataSource = products;
                productsDropDown.DataBind();

                var item = new ListItem("- vali toode -", "");
                productsDropDown.Items.Insert(0, item);

                var productId = Request.QueryString["p"] ?? string.Empty;
                if (productsDropDown.Items.FindByValue(productId) != null)
                    productsDropDown.SelectedValue = productId;
            }
            catch (Exception ex)
            {
                Logger.LogException(ex);
            }
            noLevelBlock.Visible = false;
            level1Block.Visible = false;
            level2Block.Visible = false;
            productBlock.Visible = false;

            //var l1 = CompanyQueryManager.GetSelectedLevel1();
            //var l2 = CompanyQueryManager.GetSelectedLevel3();
            var l1 = repository.GetActiveLevel1();
            var l3 = repository.GetActiveLevel3();
            var p = repository.GetActiveProduct();

            if (l3 != null)
            {
                level2TitleLink.InnerText = l3.Title;
                level2TitleLink.HRef = SPContext.Current.Web.Url + "/Lehed/default.aspx?l3=" + l3.Id;
                //productsRepeater.DataSource = CompanyQueryManager.GetProducts();
                productsRepeater.DataSource = repository.GetProductResults();
                productsRepeater.DataBind();
                level2Block.Visible = true;
            }
            else if (l1 != null)
            {
                level1TitleLink.InnerText = l1.Title;
                level1TitleLink.HRef = "/firmad/Lehed/Default.aspx?l1=" + l1.Id;
                level1Block.Visible = true;
            }              
            else if(p != null)
            {
                productTitleLink.InnerText = p.Title;
                productTitleLink.HRef = "/firmad/Lehed/Default.aspx?p=" + p.Id;
                productBlock.Visible = true;

                productLevel1.DataSource = repository.GetLevel3ForProduct(p);
                productLevel1.DataBind();
                productLevel1.Items.Insert(0, new ListItem("-vali valdkond-", string.Empty));

            }
            else if(SPContext.Current.ListItem != null)
                if(SPContext.Current.ListItem.File.Name.ToLower()=="default.aspx")
                    noLevelBlock.Visible = true;
        }

        protected void ProductsDropDownSelectedIndexChanged(object sender, EventArgs e)
        {
            var pId = productsDropDown.SelectedValue;
            var query = string.Empty;

            /*if (!string.IsNullOrEmpty(Request.QueryString["l1"]))
                query += "&l1=" + Request.QueryString["l1"];
            if (!string.IsNullOrEmpty(Request.QueryString["l3"]))
                query += "&l3=" + Request.QueryString["l3"];*/
            if (!string.IsNullOrEmpty(pId))
                query += "&p=" + pId;

            if (query.Length > 0)
                query = query.Substring(1);

            Response.Redirect("/firmad/Lehed/Default.aspx?" + query);
        }

        protected void ProductsRepeaterItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.DataItem == null)
                return;

            var product = (IoProduct)e.Item.DataItem;

            var link = (HtmlAnchor)e.Item.FindControl("productLink");
            link.HRef = product.Url; // "/firmad/Lehed/Default.aspx?p=" + product.Id;
            link.InnerText = product.Title;
            link.ID += "_" + e.Item.ItemIndex;
        }
    }
}
